package own.stu.jobgib.playown.grpc.client;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import own.stu.jobgib.playown.grpc.proto.GreeterGrpc;
import own.stu.jobgib.playown.grpc.proto.HelloRequest;

import java.util.concurrent.TimeUnit;

public class HelloWorldClient {

    private final GreeterGrpc.GreeterBlockingStub blockingStub;

    public HelloWorldClient(Channel channel) {
        this.blockingStub = GreeterGrpc.newBlockingStub(channel);
    }


    public void greet(String name) {
        HelloRequest request = HelloRequest.newBuilder()
                .setName(name)
                .build();

        blockingStub.sayHello(request);
        System.out.println("greet: " + name);
    }

    public static void main(String[] args) throws InterruptedException {
        String user = "xxx";

        ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:8999")
                .usePlaintext()
                .build();

        try {
            HelloWorldClient client = new HelloWorldClient(channel);
            client.greet(user);
        } finally {
            // ManagedChannels use resources like threads and TCP connections. To prevent leaking these
            // resources the channel should be shut down when it will no longer be used. If it may be used
            // again leave it running.
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
    }
}
